/**
 * Created by zhaizy on 2015/3/16.
 */

angular.module('main.controller', ["myservice"])

.controller("HomeController", function($scope, $state, $ionicPopup, $ionicHistory, $http, $sce, $q) {

    $scope.urlItems = [];

    $scope.datas = [];

    $scope.itemClick = function() {
        $state.go("quote.platform");
    }

    $scope.clickImg = function(url) {
        alert(url);
    }


    $scope.selectGet = function() {
        console.log("@@##select get!");

        $state.goForResult("testGetForResult", $scope.data).then(function(result) {
            $scope.data = result;
            //alert("the test result is " + result);
        });

    }

    var html = $http({
        url: "http://info.go.baoxian.com/list-94-1.html",
        method: "GET"
    }).success(function(result) {
        var parse = new DOMParser();
        var doc = parse.parseFromString(result, 'text/html');
        var lis = angular.element(doc).find("ul").find("li");
        console.log(lis);

        //li下的元素
        for (var i = 0; i < lis.length; i++) {

            var urlItem = {};

            var li = lis[i];

            var a = angular.element(li).find("a");

            var a_attrs = a[0].attributes;
            for (var ii = 0; ii < a_attrs.length; ii++) {
                var a_attr = a_attrs[ii];
                console.log("@@##a_attrs:" + a_attr.name + " " + a_attr.value);
            }

            var img = angular.element(li).find("img");
            var img_attrs = img[0].attributes;
            for (var jj = 0; jj < img_attrs.length; jj++) {
                var img_attr = img_attrs[jj];
                console.log("@@##img_attrs:" + img_attr.name + " " + img_attr.value);
            }

            //$scope.datas.push($sce.trustAsHtml(li.innerHTML));
            var els = li.childNodes;

            //li下的元素下的
            for (var j = 0; j < els.length; j++) {
                var el = els.item(j);
                console.log(el.innerHTML);

                var nodes = el.childNodes;
                if (nodes) {
                    for (var l = 0; l < nodes.length; l++) {
                        var node = nodes.item(l);

                        var item = {};
                        item.nodeName = node.nodeName;
                        var nodeattrs = node.attributes;
                        for (var k = 0; k < nodeattrs.length; k++) {
                            var nodeattr = nodeattrs[k];
                            console.log("@@##attr:" + nodeattr.name + " " + nodeattr.value);
                            item[nodeattr.name] = nodeattr.value;

                            urlItem[nodeattr.name] = nodeattr.value;
                        }

                        //urlItems.push(item);
                        //urlItems.push(urlItem)
                    }
                }

                var item = {};
                item.nodeName = el.nodeName;

                var attrs = el.attributes;
                for (var k = 0; k < attrs.length; k++) {
                    var attr = attrs[k];
                    console.log("@@##attr:" + attr.name + " " + attr.value);
                    item[attr.name] = attr.value;

                    urlItem[attr.name] = attr.value;
                }

                //urlItems.push(item);

            }

            $scope.urlItems.push(urlItem);

        }

        console.log(JSON.stringify($scope.urlItems));


    });


    $scope.goBack = function() {

        var confirmPopup = $ionicPopup.confirm({
            title: '提示',
            template: '确定退出到登录页面?'
        });
        confirmPopup.then(function(res) {
            if (res) {
                $ionicHistory.goBack();
                console.log('You are sure');
            } else {
                console.log('You are not sure');
            }
        });
    }


})

.controller("LoginController", function(socket, $scope, $state, zzbHttp, $ionicPopover, zzbLocalCache, PreferenceKey) {

    //$scope.username = zzbLocalCache.get(PreferenceKey.PRE_KEY_USER_NAME);
    //$scope.password = zzbLocalCache.get(PreferenceKey.PRE_KEY_PASSWORD);

    $scope.goChat = function(user) {
        console.log("@@##login gochat!");

        //服务器返回格式统一为 {code:0,msg:"success"}
        socket.emit("login",{userid:user.username,username:user.username},function(data){
            console.log("@@##login from server:"+JSON.stringify(data));
            if (data.code==0) {
                 $state.go("chatRoom",{username:user.username});
            };

        });

        socket.on("login",function(data){
             console.log("@@##login from server:"+JSON.stringify(data));
            if (data.code==0) {
                 $state.go("chatRoom",{username:user.username});
            };
        });

    }

    $scope.signIn = function(user) {

        var result = $state.go("home");

        if (result) {
            return;
        }
        //zzbHttp.post({
        //    CmdType: "FHBX",
        //    CmdModule: "SSO",
        //    CmdId: "Login"
        //}, {
        //    Username: user.username,
        //    Password: user.password,
        //    Platform: "android",
        //    IMEI: "000000"
        //}, "正在登录中...").then(function (result) {
        //    console.log("@@##login result is :" + result);
        //}, function (error) {
        //
        //});

        zzbHttp.login({
            username: user.username,
            password: user.password
        }, {}, "正在登录中...").then(function(result) {
            if (result) {
                zzbHttp.getAgentInfo().then(function(data) {
                    console.log("@@##agent info:" + JSON.stringify(data));
                    $state.go("home");
                }, function(error) {
                    alert(error)
                });
            }
        }, function(result) {
            alert("error:" + result);
        });


        //$state.go("home");
    }

    $scope.setting = function() {
        $state.go("setting");
    }

    // .fromTemplate() method
    var template = '<ion-popover-view><ion-header-bar> <h1 class="title">My Popover Title</h1> </ion-header-bar> <ion-content> Hello! </ion-content></ion-popover-view>';

    $scope.popover = $ionicPopover.fromTemplate(template, {
        scope: $scope
    });

    // .fromTemplateUrl() method
    $ionicPopover.fromTemplateUrl('my-popover.html', {
        scope: $scope
    }).then(function(popover) {
        $scope.popover = popover;
    });


    $scope.openPopover = function($event) {
        
        $scope.popover.show($event);
    };
    $scope.closePopover = function() {
        $scope.popover.hide();
    };
    //Cleanup the popover when we're done with it!
    $scope.$on('$destroy', function() {
        $scope.popover.remove();
    });
    // Execute action on hide popover
    $scope.$on('popover.hidden', function() {
        // Execute action
    });
    // Execute action on remove popover
    $scope.$on('popover.removed', function() {
        // Execute action
    });
})

.controller("SettingController", function($scope, zzbLocalCache, $ionicPopup, dialogService, zzbHttp, $ionicHistory, $state) {

    var myUrl = zzbLocalCache.get("custom");
    $scope.url = myUrl;
    console.log("@@##the custom url is " + myUrl);

    //MSM_HEADER CmdType=FHBX;CmdModule=ORDER;CmdId=Search;CmdVer=1.0.0;ToKen=
    //MSM_PARAM uuid=B88C62ADF49D4343AA76829209CCD614;orderStatus=NTP;startDate=2015-02-18;max=10;offset=0
    $scope.evclick3 = function() {
        zzbHttp.post({
            CmdType: "FHBX",
            CmdModule: "ORDER",
            CmdId: "Search"
        }, {
            uuid: "B88C62ADF49D4343AA76829209CCD614",
            orderStatus: "NTP"
        }, "正在加载中...").then(function(data) {
            alert(JSON.stringify(data));
        });
    }

    $scope.evclick2 = function() {
        var items = [{
            name: "选择1",
            value: "111",
            selected: true
        }, {
            name: "选择2",
            value: "2222",
            selected: true
        }, {
            name: "选择3",
            value: "3333",
            selected: true
        }];
        dialogService.showSelectDialog($scope, "标题", items).then(function(result) {
            alert(result);
        }, function(error) {
            alert(error);
        }, function(percentComplete) {

        });
    }

    $scope.evclick = function(target) {

        //var evCache = $cacheFactory("zzb_setting");
        $scope.data = [{
            ev: "net",
            url: "http://zzb.baoxan.net/cpmap/access/"
        }, {
            ev: "org",
            url: "http://zzb.baoxan.org/cpmap/access/"
        }, {
            ev: "生产",
            url: "http://zzb.baoxian.com/cpmap/access/"
        }, {
            ev: "准生产",
            url: "http://zzb.52zzb.com/cpmap/access/"
        }, {
            ev: "自定义",
            url: myUrl
        }];
        // An elaborate, custom popup
        //zzbLocalCache.put("default", "http://zzb.baoxan.org/cpmap/access/");
        var myPopup = $ionicPopup.show({
            templateUrl: "templates/component/evdialog.html",
            title: '请选择环境',
            subTitle: '',
            scope: $scope,
            buttons: [{
                text: 'Cancel'
            }, {
                text: '<b>Save</b>',
                type: 'button-positive',
                onTap: function(e) {
                    if (!$scope.data.url) {
                        //don't allow the user to close unless he enters wifi password

                        //如果链接为空就弹出框来输入
                        var dialog = $ionicPopup.show({
                            template: '<input type="text" value="{{url}}" ng-model="data.url">',
                            title: '请输入自定义地址',
                            scope: $scope,
                            buttons: [{
                                text: 'Cancel'
                            }, {
                                text: '<b>Save</b>',
                                type: 'button-positive',
                                onTap: function(e) {
                                    if (!$scope.data.url) {
                                        //don't allow the user to close unless he enters wifi password
                                        e.preventDefault();
                                    } else {
                                        zzbLocalCache.put("custom", $scope.data.url);
                                        return $scope.data.url;
                                    }
                                }
                            }]
                        });
                        dialog.then(function(res) {
                            console.log('Tapped!', res);
                            dialog.close();
                        });
                        //$timeout(function () {
                        //    dialog.close(); //close the popup after 3 seconds for some reason
                        //}, 3000);


                        e.preventDefault();
                    } else {
                        alert("the sex is " + $scope.data.url);
                        //this.value = $scope.data.url;

                        $scope.url = $scope.data.url;

                        zzbLocalCache.put("custom", $scope.url);

                        return $scope.data.url;
                    }
                }
            }]
        });
        myPopup.then(function(res) {
            console.log('Tapped!', res);
        });
        //$timeout(function () {
        //    myPopup.close(); //close the popup after 3 seconds for some reason
        //}, 3000);


    };


})
